<template>
  <div class="text-poptip">
    <a-tooltip placement="top" v-if="isShowTooltip">
      <template #title>
        <div style="max-width: 500px">{{ source }}</div>
      </template>
      <div class="linkTo" @mouseover="onMouseOver(keyid)">
        <span :ref="keyid" :class="keyid">{{ source }}</span>
      </div>
    </a-tooltip>
    <div class="linkTo" @mouseover="onMouseOver(keyid)" v-else>
      <span :ref="keyid" :class="keyid">{{ source }}</span>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, defineProps, watch } from 'vue';

const props = defineProps<{
  keyid: string;
  source: string | number;
}>();

const isShowTooltip = ref(false);

const onMouseOver = (str: string) => {
  const tag = ref<HTMLElement | null>(null);
  watch(
    () => props.keyid,
    () => {
      tag.value = document.querySelector(`.${props.keyid}`) as HTMLElement;
    },
    { immediate: true },
  );

  if (tag.value) {
    const parentWidth = tag.value.parentNode ? (tag.value.parentNode as HTMLElement).offsetWidth : 0; // 获取元素父级可视宽度
    const contentWidth = tag.value.offsetWidth; // 获取元素可视宽度
    isShowTooltip.value = contentWidth > parentWidth;
  }
};
</script>
<style lang="scss" scoped>
.ivu-tooltip {
  width: 100%;
  display: inline-block;
  text-align: center;
  color: #ffffff;
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 0 0.3125rem;
}
.ivu-tooltip-rel {
  width: 100%;
}
.linkTo {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  height: 100%;
  text-overflow: ellipsis;
  span {
    cursor: pointer;
    font-size: 12px;
  }
}
</style>
